<template>
    <div class="tags_container">
        <el-tag class="keyword_tag" v-for="(tag, index) in defaultKeywordTags"
                :key="index" size="" :closable="isEditFlag"
                @close="handleClose(tag)">
            {{ tag }}
        </el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue"
                  ref="saveTagInput" @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm" />
        <el-button v-if="!inputVisible && isEditFlag" class="button-new-tag"
                   icon="el-icon-plus" @click="showInput">添加
        </el-button>
    </div>
</template>

<script>
export default {
    name: "KeywordComponent",
    props: {
        list: {
            type: Array,
            default() {
                return [];
            }
        },
        isEditFlag: {
            type: Boolean,
            default() {
                return true;
            }
        },
    },
    data() {
        let _this = this;
        return {
            defaultKeywordTags: [],//'标签一', '标签二', '标签三', '标签四', '标签五'
            inputVisible: false,
            inputValue: '',
        };
    },
    watch: {
        list: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        init() {
            let _this = this;
            _this.defaultKeywordTags = _this.list;
        },
        handleClose(tag) {
            let _this = this;
            _this.defaultKeywordTags.splice(_this.defaultKeywordTags.indexOf(tag), 1);
        },
        showInput() {
            let _this = this;
            _this.inputVisible = true;
            _this.$nextTick(_ => {
                _this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm() {
            let _this = this;
            let inputValue = _this.inputValue;
            if (inputValue) {
                _this.defaultKeywordTags.push(inputValue);
                _this.$emit('change', _this.defaultKeywordTags);
            } else {
                _this.inputVisible = false;
                return;
            }
            _this.inputVisible = true;
            _this.inputValue = '';
        }
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.tags_container {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 5px;
    flex-flow: wrap;

    .keyword_tag {
        height: 24px;
        line-height: 24px;
    }

    .input-new-tag {
        width: 90px;
    }
}
</style>
